//
//  StatusDAL.swift
//  weibopush
//
//  Created by 龚欣 on 15/7/14.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit

class StatusDAL: NSObject {

    class func loadStatus(since_id : Int, max_id : Int,finish:(array : [[String : AnyObject]]?,error : NSError?)->()){
        //1 判断缓存数据
        StatusDAL.loadCacheStatus(since_id, max_id: max_id) { (array) -> () in
            //2 如果有就返回缓存数据
            if !array.isEmpty{
                finish(array: array, error: nil)
                return
            }
        
        
        //3 如果没有从网络加载
        NetworkTool.sharedNetworkTool().loadData(since_id, max_id: max_id) { (array, error) -> () in
            
            if array != nil {
        //4 加载的数据如果不为空就存入数据库
                saveData(array!)
            }
            
            finish(array: array, error: error)
            
        }
    }
    }
    
   private class func loadCacheStatus(since_id : Int, max_id : Int,finished : (array : [[String : AnyObject]])->()){
        assert(sharedAccount != nil, "必须登陆之后才能执行此方法")
        
        var sql = "SELECT statusID,status,userID FROM T_Status \n" +
        "WHERE userID = \(sharedAccount!.uid!)\n"
        
        if since_id > 0 {
            sql += "AND statusID > \(since_id)\n"
        }
        
        if max_id > 0 {
            sql += "AND statusID < \(max_id)\n"
        }
        
        sql += "ORDER BY statusID DESC LIMIT 20;"
        //一定要测试SQLite代码写的对不对~~~~
        print(sql)
        
        SQLiteManager.sharedManager.queue?.inTransaction({ (db, _) -> Void in
            let rs = db.executeQuery(sql)!
            var array = [[String : AnyObject]]()
            
            while rs.next() {
                let str = rs.stringForColumn("status")
                
                let data = str.dataUsingEncoding(NSUTF8StringEncoding)!
                let dict = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as! [String : AnyObject]
                array.append(dict)
            }
                finished(array: array)
        })
        
    }
    
    /// MARK: 保存数据
   private class func saveData(array : [[String : AnyObject]]){
        
        assert(sharedAccount != nil, "必须登录才能执行此方法")
        
        let userID = sharedAccount?.uid
        
        let sql = "INSERT OR REPLACE INTO T_Status\n" +
        "('statusID','status','userID')\n" +
        "VALUES\n" +
        "(?,?,?)"
        
        for dict in array {
            let statusID = dict["id"] as! Int
            
            let data = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0))
            let status = NSString(data: data, encoding: NSUTF8StringEncoding)
            
            SQLiteManager.sharedManager.queue?.inTransaction({ (db, callback) -> Void in
                if !db.executeUpdate(sql,statusID,status!,userID!) {
                    callback.memory = true
                }
            
            })
        }
        
    }
}
